﻿package  {
	import flash.utils.Timer;
	import flash.display.BitmapData;
	import flash.display.Bitmap;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.KeyboardEvent;
	import flash.ui.KeyboardType;
	import flash.ui.Keyboard;
	import flash.display.Stage;
	
	public class BaseGame {			
		
		protected var displayContainer : MovieClip;
		
		//game loop 		
		private var gameLoop : GameLoop;
		
		//input
		public var input:Input ;
		
		// buat render
		protected var screenWidth : int;
		protected var screenHeight : int;
		protected var canvasBD : BitmapData
		protected var canvasBitmap : Bitmap
		
		//untuk menghitung FPS
		protected var frameRate:int;
		private var frameCounter:int;
		private var timeFPSCount:Number;		

		//menyimpan input yang masuk		

		public function BaseGame(displayContainer:MovieClip) {						
			this.screenWidth = displayContainer.stage.stageWidth;
			this.screenHeight = displayContainer.stage.stageHeight;						
			canvasBD = new BitmapData(screenWidth, screenHeight,false,0x000000); 
			canvasBitmap = new Bitmap(canvasBD);						
			this.displayContainer = displayContainer;
			displayContainer.addChild(canvasBitmap);							
			displayContainer.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);			
			displayContainer.stage.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
			input = new Input();					
		}
		
		public function initialize() {
			frameRate = 0;
			frameCounter = 0;
			timeFPSCount = 0;			
		}
		
		public function loadContent() {
			//override			
			initGameLoop();	
		}
		
		public function unloadContent() {
			//override
			displayContainer.stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownListener);
			displayContainer.stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpListener);
		}
		
		private function initGameLoop() {						
			gameLoop = new GameLoop(this);
			gameLoop.start();
		}		

		public function update(elapsedTime:Number) {			
			//override
		}								
		
		public function render(elapsedTime:Number) {			
			frameCounter++;
			timeFPSCount += elapsedTime;						
			if(timeFPSCount >= 1) {
				timeFPSCount = 0;
				frameRate = frameCounter
				frameCounter = 0;			
				
			}						
			//override			
		}
		
		public function keyDownListener(e:KeyboardEvent) {			
			input.keyPressed(e.keyCode);
		}
		
		public function keyUpListener(e:KeyboardEvent) {
			input.keyReleased(e.keyCode);			
		}
		
		public function getScreenWidth():int {
			return screenWidth;						
		}
		
		public function getScreenHeight():int {
			return screenHeight;
		}
	}
	
}
